import { 
    getBoardList, addBoard,
    getEnergySumInfo, getCOPTrend, getEERTrend, getColdTrend, test
} from '../services/boardService';
// import { getFields, getFieldAttrs } from '../services/fieldsService';
// import { getRecordList, getWarningDetail } from '../services/alarmService';
// import { getRankAndGrade } from '../services/analyzeMachService';
// import { getSaveSpace, getMonitorInfo } from '../services/monitorService';
import moment from 'moment';

let date = new Date();

let defaultList = [
    {
        label: '默认看板',
        key:'0', 
        dataCardList: [
            { key: 'a', a: 1 },
            { key: 'b', a: 1 },
            { key: 'c', a: 1 },
            { key: 'd', a: 1 },
            { key: 'e', a: 1 },
            { key: 'f', a: 1 },
            { key: 'g', a: 1 },
            { key: 'h', a: 1 },
            { key: 'i', a: 1 },
            { key: 'j', a: 1 },
            { key: 'k', a: 1 },
            { key: 'l', a: 1 },
            { key: 'm', a: 1 },
            { key: 'n', a: 1 },
            { key: 'o', a:1 },
            { key: 'p', a:1 },
            { key: 'q', a:1 },
            { key: 'r', a:1 },
            { key: 's', a:1 },
            { key: 't', a:1 },
            { key: 'u', a:1 },
            { key: 'v', a:1 },
            { key:'w', a:1 },
            { key:'x', a:1 }
        ],
        chartCardList: [
            { key: 'A', a: 1 },
            { key: 'B', a: 1 },
            { key: 'C', a: 1 },
            { key: 'D', a: 1 },
            { key: 'E', a: 1 },
            { key: 'F', a: 1 },
            { key: 'G', a: 1 },
            { key: 'H', a: 1 },
            { key: 'I', a: 1 },
            { key: 'J', a: 1 },
            { key: 'K', a: 1 },
            { key: 'L', a: 1 }
        ]
    }
];
const initialState = {
    boardList:[],
    currentIndex: '0',
    loaded:false,
    COPInfo:{},
    sumInfo:{},
    // 组态看板
    canvasBoard:{},
    fieldMaps: {
        // 能耗概况字段
        a: {
            title: '本月总能耗',
            dataIndex:'cost',
            unit: 'kwh',
            subArr: [
                { title: '同比', dataIndex:'sameRate', unit: '%' },
                { title: '环比', dataIndex:'adjoinRate', unit: '%' },
            ],
        },
        b: {
            title:'本年节俭成本',
            dataIndex:'cost',
            unit:'元',
            subArr: [
                { title: '同比', dataIndex: 'sameRate', unit: '%' },
                { title: '环比', dataIndex: 'adjoinRate', unit: '%' },
            ]
        },
        c: { 
            title: '本年碳排放', 
            dataIndex:'ele',
            unit:'tco2e',
            subArr: [
                { title: '同比', dataIndex: 'sameRate', unit: '%' },
                { title: '环比', dataIndex: 'adjoinRate', unit: '%' },
            ]
        },
        d: { 
            title: '本年标煤', 
            dataIndex:'water',
            unit:'t',
            subArr: [
                { title: '同比', dataIndex: 'sameRate', unit: '%' },
                { title: '环比', dataIndex: 'adjoinRate', unit: '%' },
            ]
        },
        e: { 
            title: '本年节能量', 
            dataIndex:'gas',
            unit:'kwh',
            subArr: [
                { title: '同比', dataIndex: 'sameRate', unit: '%' },
                { title: '环比', dataIndex: 'adjoinRate', unit: '%' },
            ]
        },
        f: { 
            title: '本年节能百分比', 
            dataIndex:'steam',
            unit:'%',
            subArr: [
                { title: '同比', dataIndex: 'sameRate', unit: '%' },
                { title: '环比', dataIndex: 'adjoinRate', unit: '%' },
            ]
        },
        g: { 
            title:'本月总成本',
            dataIndex:'carbonEnergy',
            unit:'元',
            subArr:[
                { title:'同比', dataIndex:'sameCarbonEnergyRate', unit:'%'},
                { title:'环比', dataIndex:'adjoinCarbonEnergyRate', unit:'%' }
            ]
        },
        h: { 
            title:'本年总成本',
            dataIndex:'energy',
            unit:'元',
            subArr:[
                { title:'同比', dataIndex:'sameEnergyRate', unit:'%'},
                { title:'环比', dataIndex:'adjoinEnergyRate', unit:'%' }
            ]
        },
        i: { 
            title:'本月冷量单价',
            dataIndex:'carbonEnergy',
            unit:'kwh/GJ',
            hasSymbol:true
        },
        j: { 
            title:'主机能耗占比',
            dataIndex:'energy',
            unit:'t',
            hasSymbol:true
        },
        k: {
            title:'辅机能耗占比',
            dataIndex:'energy',
            unit:'kwh/GJ',
            hasSymbol:true
        },
        // 系统能效
        l:{
            title:'当前EER',
            dataIndex:'localOEE',
            unit:'',
            hasSymbol:true
        },
        m:{
            title:'累计制冷量',
            dataIndex:'totalCold',
            unit:'GJ',
            subArr:[
                { title:'同比', dataIndex:'totalColdYOY', unit:'%'},
                { title:'环比', dataIndex:'totalColdChain', unit:'%' }
            ]
        },
        n:{
            title:'本月告警数',
            dataIndex:'localMonthWarningNum',
            unit:'件',
            color:'#f53f3f',
            subArr:[
                { title:'通讯异常', color:'#f53f3f', dataIndex:'ele', unit:'件'},
                { title:'指标越限', color:'#f53f3f', dataIndex:'quotaLimit', unit:'件'},
            ]
        },
        o:{
            title:'制冷量',
            dataIndex:'total',
            unit:'kw',
            color:'#f53f3f',
            subArr:[
                { title:'同比', dataIndex:'sameEnergyRate', unit:'%'},
                { title:'环比', dataIndex:'adjoinEnergyRate', unit:'%' }
            ]
        },
        p:{
            title:'冷却COP',
            dataIndex:'lqCop',
            unit:'',
            color:'#f53f3f',
            hasSymbol:true
        },
        q:{
            title:'冷冻COP',
            dataIndex:'ldCop',
            unit:'',
            color:'#f53f3f',
            hasSymbol:true
        },
        r:{
            title:'管道系数',
            dataIndex:'pipelineFactorS',
            unit:'',
            color:'#f53f3f',
            hasSymbol:true
        },
        s:{
            title:'冷却泵效率',
            dataIndex:'lqbEfficiency',
            unit:'',
            color:'#f53f3f',
            hasSymbol:true
        },
        t:{
            title:'冷冻泵效率',
            dataIndex:'ldbEfficiency',
            unit:'',
            color:'#f53f3f',
            hasSymbol:true
        },
        u:{
            title:'系统COP',
            dataIndex:'sysCop',
            unit:'',
            color:'#f53f3f',
            hasSymbol:true
        },
        v:{
            title:'系统总功率',
            dataIndex:'sysTotalPower',
            unit:'kw',
            color:'#f53f3f',
            subArr:[
                { title:'同比', dataIndex:'sysTotalPowerYOY', unit:'%'},
                { title:'环比', dataIndex:'sysTotalPowerChain', unit:'%' }
            ]
        },
        w:{
            title:'主机总功率',
            dataIndex:'masterPower',
            unit:'kw',
            color:'#f53f3f',
            subArr:[
                { title:'同比', dataIndex:'masterPowerYOY', unit:'%'},
                { title:'环比', dataIndex:'masterPowerChain', unit:'%' }
            ]
        },
        x:{
            title:'辅机总功率',
            dataIndex:'vicePower',
            unit:'kw',
            color:'#f53f3f',
            subArr:[
                { title:'同比', dataIndex:'vicePowerYOY', unit:'%'},
                { title:'环比', dataIndex:'vicePowerChain', unit:'%' }
            ]
        }
    },
    chartMaps:{
        A:'用电量趋势',
        B:'月节能目标',
        C:'能耗日历',
        D:'用水费用趋势',
        E:'碳排量',
        F:'标煤趋势',
        G:'冷量单价',
        H:'费用占比',
        I:'COP趋势',
        J:'实时告警',
        K:'ERR趋势',
        L:'冷量趋势'
    },
    // 数据卡片状态
    statusSourceData: {}
};

export default {
    namespace: 'board',
    state: initialState,
    effects: {
        *init(action, { put, select, call }){
            // yield put.resolve({ type:'fields/init' });
            yield put.resolve({ type:'fetchBoardList'});
            yield put({ type:'getResult'});
            yield put({ type:'fetchEnergySumInfo'});
            // yield put({ type:'fetchTotalCost'});
            // yield put({ type:'fetchYearCarbon'});
            // yield put({ type:'fetchRankAndGrand'});
            // yield put({ type:'fetchMonthWarningInfo'});
            // yield put({ type:'fetchSaveSpace'});
            // yield put({ type:'fetchEnergyQuota'});
        },
        // 组态看板接口
        *fetchCanvasBoard(action, { call, put, select }){
            let { user:{ companyId }} = yield select();
            let { code, data, message } = yield call(getBoardList, { companyId, type:'2' });
            if ( code === 200 ) {
                yield put({ type:'getCanvasBoardResult', payload:{ data }});
            }
        },
        *setCanvasBoard(action, { call, put, select }){
            let { user:{ companyId }} = yield select();
            let { resolve, reject, result } = action.payload || {};
            let { code, data, message } = yield call(addBoard, { companyId, type:'2', dashboardsDetail:result });
            if ( code === 200 ) {
                if ( resolve ) resolve();
                yield put({ type:'fetchCanvasBoard'});
            } else {
                if ( reject ) reject(message);
            }
        },
        *fetchBoardList(action, { call, put, select }){
            let { user:{ companyId }} = yield select();
            let { code, data, message } = yield call(getBoardList, { companyId, type:'1' });
            if ( code === 200 ){
                yield put({ type:'getBoardListResult', payload:{ data:data }});
            }
        },
        *setBoardAsync(action, { call, put, select }){
            let { user:{ companyId }} = yield select();
            let { resolve, reject, content } = action.payload || {};
            let { code, data, message } = yield call(addBoard, { companyId, type:'1', dashboardsDetail:content });
            if ( code === 200 ){
                if ( resolve ) resolve();
                yield put({ type:'fetchBoardList'});
            } else {
                if ( reject ) reject(message);
            }
        },
        // 状态请求数据
        *fetchEnergySumInfo(action, { put, call, select }){
            let { user:{ companyId }} = yield select();
            let { code, data, message } = yield call(getEnergySumInfo, { companyId });
            if ( code === 200 ) {
                yield put({ type:'getStatusDataResult', payload:{ data, fields:null }});
            }
        },
        *fetchYearCarbon(action, { put, call, select }){
            let { user:{ company_id }} = yield select();
            let { data } = yield call(getYearAndMonthCoal, { company_id });
            if ( data && data.code === '0'){
                yield put({ type:'getStatusDataResult', payload:{ data:data.data, fields:[{ key:'g', map:'year' }, { key:'h', map:'year' }, { key:'i', map:'month' }, { key:'j', map:'month' }] }});
            }
        },
        *fetchRankAndGrand(action, { put, call, select }){
            let date = new Date();
            let { data } = yield call(getRankAndGrade,{ begin_date:moment(date).startOf('month').format('YYYY-MM-DD'), end_date:moment(date).endOf('month').format('YYYY-MM-DD'), time_type:'2' })
            if ( data && data.code === '0') {
                yield put({ type:'getStatusDataResult', payload:{ data:data.data, fields:[{ key:'k', map:'' }, { key:'l', map:'' }]}});
            }
        },
        *fetchMonthWarningInfo(action, { put, call, select }){
            let { user:{ company_id }} = yield select();
            let date = new Date();
            let { data } = yield call(getWarningDetail, { company_id, begin_date:moment(date).startOf('month').format('YYYY-MM-DD'), end_date:moment(date).endOf('month').format('YYYY-MM-DD') });
            if ( data && data.code === '0') {
                yield put({ type:'getStatusDataResult', payload:{ data:data.data, fields:[{ key:'m', map:'codeCountArr' }]}});
            }
        },
        *fetchSaveSpace(action, { put, call, select }){
            let { user:{ company_id }} = yield select();
            let date = new Date();
            let { data } = yield call(getSaveSpace, { company_id, begin_date:moment(date).startOf('month').format('YYYY-MM-DD'), end_date:moment(date).endOf('month').format('YYYY-MM-DD') });
            if ( data && data.code === '0'){
                let { eleCost, baseCost, adjustCost } = data.data.costInfo;
                yield put({ type:'getStatusDataResult', payload:{ data:{ total:( eleCost || 0 ) + ( baseCost || 0 ) + ( adjustCost || 0 ) }, fields:[{ key:'n', map:'' }]}})
            }
        },
        *fetchEnergyQuota(action, { put, call, select }){
            let { user:{ company_id }, fields:{ energyMaps }} = yield select();
            let { data } = yield call(getMonitorInfo, { company_id });
            if ( data && data.code === '0') {
                let { energyInfo, quota } = data.data;
                // 重新生成数据卡片列表对应的数据结构
                if ( energyInfo ) {
                    Object.keys(energyInfo).forEach(key=>{
                        energyInfo[key].quota = quota[key];
                        energyInfo[key].type_name = energyMaps[key].type_name;
                        energyInfo[key].ratio =  quota[key] ? ( energyInfo[key].cost / quota[key] * 100 ).toFixed(1) : '0.0';
                    })
                }
                yield put({ type:'getStatusDataResult', payload:{ data:energyInfo, fields:[{ key:'c', map:'ele' }, { key:'d', map:'water'}, { key:'e', map:'gas'}, { key:'f', map:'steam' }]}});
            }
        },
        // ---------------图表卡片请求数据
        // COP趋势
        *fetchCOPTrend(action, { put, call, select }){
            let { user:{ companyId }} = yield select();
            let { resolve, reject, startDate, endDate, timeType  } = action.payload || {};
            let { code, data, message } = yield call(getCOPTrend, { companyId, timeType, beginDate:startDate.format('YYYY-MM-DD'), endDate:endDate.format('YYYY-MM-DD') })
            if ( code === 200 ) {
                if ( resolve ) resolve(data);
            } else {
                if ( reject ) reject(message);
            }
        },
        // EER趋势
        *fetchEERTrend(action, { put, call, select }){
            let { user:{ companyId }} = yield select();
            let { resolve, reject, startDate, endDate, timeType  } = action.payload || {};
            let { code, data, message } = yield call(getEERTrend, { companyId, timeType, beginDate:startDate.format('YYYY-MM-DD'), endDate:endDate.format('YYYY-MM-DD') })
            if ( code === 200 ) {
                if ( resolve ) resolve(data);
            } else {
                if ( reject ) reject(message);
            }
        },
        *fetchColdTrend(action, { put, call, select }){
            let { user:{ companyId }} = yield select();
            let { resolve, reject, startDate, endDate, timeType  } = action.payload || {};
            let { code, data, message } = yield call(getColdTrend, { companyId, timeType, beginDate:startDate.format('YYYY-MM-DD'), endDate:endDate.format('YYYY-MM-DD') })
            if ( code === 200 ) {
                if ( resolve ) resolve(data);
            } else {
                if ( reject ) reject(message);
            }
        },
        // 能源成本分布
        *fetchAllEnergyCost(action, { put, call, select, all }){
            let { user:{ company_id }, fields:{ energyList, energyMaps }} = yield select();
            let { resolve, reject, timeType } = action.payload || {};
            let totalData = yield all(energyList.map(item=>(
                call(getTotalCost, { company_id, type_id:item.type_id, time_type:timeType })
            )));
            if ( totalData && totalData.length ) {
                let obj = { energyMaps };
                totalData.forEach((item, index)=>{
                    if ( index === 0 ) {
                        obj['date'] = item.data.data.date; 
                    }
                    obj[energyList[index].type_code] = item.data.data.cost;
                })
                if ( resolve ) resolve(obj);
            } else {
                if ( reject ) reject(data.msg);
            }
        },
        *fetchAlarmList(action, { put, call, select }){
            let { user:{ company_id }} = yield select();
            let { resolve, reject, warningType } = action.payload || {};
            let { data } = yield call(getRecordList, { company_id, page:1, pagesize:100, cate_code:warningType });
            if ( data && data.code === '0'){
                if ( resolve ) resolve(data.data);
            } else {
                if ( reject ) reject(data.msg);
            }
        },
        *fetchCalendar(action, { call, put, select }){
            let { user:{ company_id }} = yield select();
            let { resolve, reject, mode, year, month, attr_id, type_id } = action.payload || {};
            let { data } = yield call(getCalendarInfo, { company_id, attr_id, energy_type:type_id, year, month, time_type:mode === 'month' ? '2' : '3' });
            if ( data && data.code === '0'){
                if ( resolve ) resolve(data.data);
            } else {
                if ( reject ) reject(data.msg);
            }  
        },
        *getFields(action, { call, select }){
            let { fields:{ allFields, energyList }} = yield select();
            let { resolve, reject } = action.payload || {};
            if ( resolve ) resolve({ energyList, fieldList:allFields['ele'] ? allFields['ele'].fieldList : [] });
        },
        // 区域能耗成本排名
        *fetchFields(action, { call, select }){
            let { user:{ company_id }, fields:{ energyList }} = yield select();
            let { resolve, reject, type_id } = action.payload || {};
            type_id = type_id || energyList[0].type_id ;
            let { data } = yield call(getFields, { company_id, energy_type:type_id });
            if ( data && data.code === '0') {
                if ( resolve ) resolve({ energyList, fieldList:data.data.fields });
            } else {
                if ( reject ) reject(data.msg);
            }
        },
        *fetchFieldAttrs(action, { call, select }){
            let { resolve, reject, field_id } = action.payload || {};
            let { data } = yield call(getFieldAttrs, { field_id });
            if ( data && data.code === '0'){
                if ( data.data.list && data.data.list.length ) {
                    if ( resolve ) resolve(data.data.list[0]);
                } else {
                    if ( reject ) reject('该能源维度下没有属性节点');
                }
            } else {
                if ( reject ) reject(data.msg);
            }
        },
        *fetchAttrCost(action, { call, put, select }){
            let { user:{ company_id }, fields:{ currentField, energyList }} = yield select();
            let { resolve, reject, type_id, field_id } = action.payload || {};
            let { data } = yield call(getAttrQuota, { company_id, type_id, field_id });
            if ( data && data.code === '0' ){
                if ( resolve ) resolve(data.data);
            } else {
                if ( reject ) reject(data.msg);
            }
        },
        // 电费成本分布
        *fetchMeasureCost(action, { call, put, select }){
            try {
                let { user:{ company_id }, fields:{ currentAttr }} = yield select();
                let { resolve, reject, startDate, endDate, timeType } = action.payload || {};
                // 1：按月；2：按年
                timeType = timeType === '2' ? '1' : timeType === '3' ? '2' : timeType === '10' ? '1' : timeType ;
                let { data } = yield call(getMeasureCost, { company_id, attr_id:currentAttr.key, begin_date:startDate.format('YYYY-MM-DD'), end_date:endDate.format('YYYY-MM-DD'), time_type:timeType });
                if ( data && data.code === '0') {
                    if ( resolve ) resolve(data.data.view);
                } else {
                    if ( reject ) reject(data.msg);
                }
            } catch(err){
                console.log(err);
            }
        },
        // 碳排放
        *fetchCoalData(action, { call, put, select }){
            let { user:{ company_id }} = yield select();
            let { resolve, reject, dataType, startDate, endDate, timeType } = action.payload || {};
            // 1.碳排放 2.标煤
            let { data } = yield call(getCoalData, { company_id, time_type:timeType, data_type:dataType, begin_date:startDate.format('YYYY-MM-DD'), end_date:endDate.format('YYYY-MM-DD') });
            if ( data && data.code === '0') {
                if ( resolve ) resolve(data.data);
            } else {
                if ( reject ) reject(data.msg);
            }
        }
    },
    reducers: {
        toggleLoading(state) {
            return { ...state, isLoading: true };
        },
        getBoardListResult(state, { payload:{ data }}) {
            // 走默认看板设置
            return { ...state, boardList:data && data.dashboardsDetail ? JSON.parse(data.dashboardsDetail) : defaultList };
        },
        getCanvasBoardResult(state, { payload:{ data }}){
            return { ...state, canvasBoard:data };
        },
        getResult(state){
            return { ...state, loaded:true };
        },
        getStatusDataResult(state, { payload: { data, fields } }) {
            // 将汇总返回的字段根据KEY值分配给对应key的数据卡片
            let result = { ...data, ...state.statusSourceData };
            if ( fields ) {
                fields.map(item=>{
                    result[item.key] = item.map ? data[item.map] : data;
                });
            }            
            console.log(result);
            return { ...state, statusSourceData:result };
        },
        setCurrentIndex(state, { payload }){
            return { ...state, currentIndex:payload };
        },
        reset(state) {
            return initialState;
        }
    }
}
